package com.sls.nzdapplication.util;

import static android.content.ContentValues.TAG;
import static android.graphics.Bitmap.createBitmap;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.Layout;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sls.nzdapplication.R;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class Utils {
    private static PowerManager.WakeLock mWakeLock;
    public static InputMethodManager imm;


    Activity activity;
    public Utils(Activity activity){
        this.activity=activity;
        if(imm==null)
            imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    }


    public  void hideIMM() {
        imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public  void showIMM() {
        imm.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN);
    }

    // 距离转换
    public static String distanceFormatter(int distance) {
        if (distance < 1000) {
            return distance + "米";
        } else if (distance % 1000 == 0) {
            return distance / 1000 + "公里";
        } else {
            DecimalFormat df = new DecimalFormat("0.0");
            int a1 = distance / 1000; // 十位

            double a2 = distance % 1000;
            double a3 = a2 / 1000; // 得到个位

            String result = df.format(a3);
            double total = Double.parseDouble(result) + a1;
            return total + "公里";
        }
    }

    // 时间转换
    public static String timeFormatter(int minute) {
        if (minute < 60) {
            return minute + "分钟";
        } else if (minute % 60 == 0) {
            return minute / 60 + "小时";
        } else {
            int hour = minute / 60;
            int minute1 = minute % 60;
            return hour + "小时" + minute1 + "分钟";
        }
    }

    public static int dp2px(Context context, int dp) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    public static int px2dp(Context context, int px) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    public static void setSpannableStr(TextView textView, String str, int startIndex, int endIndex, float proporation) {
        SpannableString spannableString = new SpannableString(str);
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#393939"));
        spannableString.setSpan(colorSpan, startIndex, endIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        RelativeSizeSpan sizeSpan01 = new RelativeSizeSpan(proporation);
        spannableString.setSpan(sizeSpan01, startIndex, endIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        textView.setText(spannableString);
    }

    public static String getDateFromMillisecond(Long millisecond) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(millisecond);
        String dateStr = simpleDateFormat.format(date);
        return dateStr;
    }


    // 释放设备电源锁
    public static void releaseWakeLock() {
        if (null != mWakeLock) {
            mWakeLock.release();
            mWakeLock = null;
        }
    }

    /**
     *判断当前应用程序处于前台还是后台
     */
    public static boolean isTopActivity(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }
    public static boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(1000);
        if (myList.size() <= 0) {
            return false;
        }
        int size = myList.size();
        for (int i = 0; i < size; i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }
    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     * @param context
     * @return true 表示开启
     */
    public static final boolean isGpsOPen(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps ) {
            return true;
        }

        return false;
    }
    /**
     * 强制帮用户打开GPS
     * @param context
     */
    public static final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    public static void turnGPSOn(Context context) {
        Intent intent = new Intent("Android.location.GPS_ENABLED_CHANGE");
        intent.putExtra("enabled", true);
        context.sendBroadcast(intent);

        String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if (!provider.contains("gps")) { //if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            context.sendBroadcast(poke);
        }
    }

    public static final String APP_BAIDU_MAP = "com.baidu.BaiduMap";
    public static final String APP_AMAP = "com.autonavi.minimap";
    /**
     * 检测是否有某个应用
     * */
    public static boolean hasApp(Context ctx, String packageName) {
        PackageManager manager = ctx.getPackageManager();
        List<PackageInfo> apps = manager.getInstalledPackages(0);
        if (apps != null) {
            for (int i = 0; i < apps.size(); i++) {
                if (apps.get(i).packageName.equals(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断文件夹是否存在
     *
     * @param path
     */
    public static void createPath(String path) {
        File file = new File(path);
        if (!file.exists()) {
            try {
                // 获取父文件
                File parent = file.getParentFile();
                if( !parent.exists() ) {
                    parent.mkdirs();  //创建所有父文件夹
                }
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *  复制单个文件
     * @param oldPath 原文件路径 如：c:/fqf.txt String
     * @param newPath 复制后路径 如：f:/fqf.txt
     */
    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            createPath(newPath);

            if (oldfile.exists()) {//文件存在时
                InputStream inStream = new FileInputStream(oldPath);//读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                int value = 0 ;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread;//字节数 文件大小
                    value ++ ;  //计数
                    fs.write(buffer, 0, byteread);
                    Message msg  = new Message(); //创建一个msg对象
                    msg.what =110 ;
                    msg.arg1 = value ; //当前的value
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
        }
    }

    /**
     * 压缩文件和文件夹
     *
     * @param srcFile 要压缩的文件或文件夹
     * @param zipFile 压缩完成的Zip路径
     * @throws Exception
     */
    public static void ZipFolder(File srcFile, File zipFile) {
        try {
            //创建ZIP
            ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(zipFile));
            //压缩
            ZipFiles(srcFile.getParent() + File.separator, srcFile.getName(), outZip);
            //完成和关闭
            outZip.finish();
            outZip.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void zip(String src, String dest) throws IOException {
        //提供了一个数据项压缩成一个ZIP归档输出流
        ZipOutputStream out = null;
        try {

            File outFile = new File(dest);//源文件或者目录
            File fileOrDirectory = new File(src);//压缩文件路径
            out = new ZipOutputStream(new FileOutputStream(outFile));
            //如果此文件是一个文件，否则为false。
            if (fileOrDirectory.isFile()) {
                zipFileOrDirectory(out, fileOrDirectory, "");
            } else {
                //返回一个文件或空阵列。
                File[] entries = fileOrDirectory.listFiles();
                for (int i = 0; i < entries.length; i++) {
                    // 递归压缩，更新curPaths
                    zipFileOrDirectory(out, entries[i], "");
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //关闭输出流
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    private static void zipFileOrDirectory(ZipOutputStream out,
                                           File fileOrDirectory, String curPath) throws IOException {
        //从文件中读取字节的输入流
        FileInputStream in = null;
        try {
            //如果此文件是一个目录，否则返回false。
            if (!fileOrDirectory.isDirectory()) {
                // 压缩文件
                byte[] buffer = new byte[4096];
                int bytes_read;
                in = new FileInputStream(fileOrDirectory);
                //实例代表一个条目内的ZIP归档
                ZipEntry entry = new ZipEntry(curPath
                        + fileOrDirectory.getName());
                //条目的信息写入底层流
                out.putNextEntry(entry);
                while ((bytes_read = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytes_read);
                }
                out.closeEntry();
            } else {
                // 压缩目录
                File[] entries = fileOrDirectory.listFiles();
                for (int i = 0; i < entries.length; i++) {
                    // 递归压缩，更新curPaths
                    zipFileOrDirectory(out, entries[i], curPath
                            + fileOrDirectory.getName() + "/");
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            // throw ex;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }


    /**
     * 压缩文件
     *
     * @param folderString
     * @param fileString
     * @param zipOutputSteam
     * @throws Exception
     */
    private static void ZipFiles(String folderString, String fileString, ZipOutputStream zipOutputSteam) throws Exception {
        System.err.println(folderString);
        System.err.println(fileString);
        if (zipOutputSteam == null)
            return;
        File file = new File(folderString + fileString);
        if (file.isFile()) {
            ZipEntry zipEntry = new ZipEntry(fileString);
            FileInputStream inputStream = new FileInputStream(file);
            zipOutputSteam.putNextEntry(zipEntry);
            int len;
            byte[] buffer = new byte[4096];
            while ((len = inputStream.read(buffer)) != -1) {
                zipOutputSteam.write(buffer, 0, len);
            }
            zipOutputSteam.closeEntry();
        } else {
            //文件夹
            String fileList[] = file.list();
            System.err.println(fileList);
            //没有子文件和压缩
            if (fileList.length <= 0) {
                ZipEntry zipEntry = new ZipEntry(fileString + File.separator);
                zipOutputSteam.putNextEntry(zipEntry);
                zipOutputSteam.closeEntry();
            }
            //子文件和递归
            for (int i = 0; i < fileList.length; i++) {
                ZipFiles(folderString+fileString+"/", fileList[i], zipOutputSteam);
            }
        }
    }

    /**
     * 解压缩
     * 将zipFile文件解压到folderPath目录下.
     * @param zipFile zip文件
     * @param folderPath 解压到的地址
     * @throws IOException
     */
    public static void upZipFile(File zipFile, String folderPath) throws IOException {
        ZipFile zfile = new ZipFile(zipFile,Charset.forName("GBK"));
        Enumeration zList = zfile.entries();
        ZipEntry ze = null;
        byte[] buf = new byte[1024];
        while (zList.hasMoreElements()) {
            ze = (ZipEntry) zList.nextElement();
            if (ze.isDirectory()) {
//                Log.d(TAG, "ze.getName() = " + ze.getName());
                String dirstr = folderPath + ze.getName();
                dirstr = new String(dirstr.getBytes("8859_1"), "GB2312");
//                Log.d(TAG, "str = " + dirstr);
                File f = new File(dirstr);
                f.mkdir();
                continue;
            }
            Log.d(TAG, "ze.getName() = " + ze.getName());
            OutputStream os = new BufferedOutputStream(new FileOutputStream(getRealFileName(folderPath, ze.getName())));
            InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
            int readLen = 0;
            while ((readLen = is.read(buf, 0, 1024)) != -1) {
                os.write(buf, 0, readLen);
            }
            is.close();
            os.close();
        }
        zfile.close();
    }

    /**
     * 给定根目录，返回一个相对路径所对应的实际文件名.
     * @param baseDir     指定根目录
     * @param absFileName 相对路径名，来自于ZipEntry中的name
     * @return java.io.File 实际的文件
     */
    public static File getRealFileName(String baseDir, String absFileName) {
        new File(baseDir).mkdir();
        return new File(baseDir+"/"+absFileName);

    }

    public static void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath + fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

//生成文件

    private static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

//生成文件夹

    private static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }

    //删除文件夹和文件夹里面的文件
    public static void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
            else if (file.isDirectory())
                deleteDirWihtFile(file); // 递规的方式删除文件夹
        }
        deleteFolder(dir);

    }
    private static void deleteFolder(File dir){
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        if(dir.listFiles().length>0){
            for (File file : dir.listFiles()) {
                deleteFolder(file); // 递规的方式删除文件夹
            }
        }else{
            dir.delete();
        }

    }

    public static List<String> getFilesAllName(String path){
        //传入指定文件夹的路径　　　　
        List<String> imagePaths = new ArrayList<>();
        try {
            File file = new File(path);
            File[] files = file.listFiles();

            for(int i = 0; i < files.length; i++){
                if(checkIsImageFile(files[i].getPath())){
                    imagePaths.add(files[i].getPath());
                }
            }
        }catch (Exception e){
        }
        return imagePaths;
    }

    public static List<String> getFilesAllName4xls(String path){
        //传入指定文件夹的路径　　　　
        List<String> imagePaths = new ArrayList<>();
        try {
            File file = new File(path);
            File[] files = file.listFiles();

            for(int i = 0; i < files.length; i++){
                    imagePaths.add(files[i].getPath());
            }
        }catch (Exception e){
        }
        return imagePaths;
    }

    /**
     * 判断是否是照片
     */
    public static boolean checkIsImageFile(String fName){
        boolean isImageFile = false;
        //获取拓展名
        String fileEnd = fName.substring(fName.lastIndexOf(".") + 1,
                fName.length()).toLowerCase();
        if(fileEnd.equals("jpg") || fileEnd.equals("png") || fileEnd.equals("gif")
                || fileEnd.equals("jpeg")|| fileEnd.equals("bmp")){
            isImageFile = true;
        }else{
            isImageFile = false;
        }
        return isImageFile;
    }

    /**
     * 图标添加文字
     */
    public static Bitmap drawText2Bitmap(String text, int imgResourceId, Context mContext) {
        try {
            Resources resources = mContext.getResources();
            float scale = resources.getDisplayMetrics().density;
            Bitmap bitmap = BitmapFactory.decodeResource(resources, imgResourceId);

            Bitmap.Config bitmapConfig = bitmap.getConfig();
            // set default bitmap config if none
            if (bitmapConfig == null) bitmapConfig = Bitmap.Config.ARGB_8888;
            // resource bitmaps are imutable, so we need to convert it to mutable one
            bitmap = bitmap.copy(bitmapConfig, true);

            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // new antialised Paint
            paint.setColor(Color.rgb(110, 110, 110));       // text color - #3D3D3D
            paint.setTextSize((int)(12 * scale));           // text size in pixels
            paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY); // text shadow

            // draw text to the Canvas center
            Rect bounds = new Rect();
            paint.getTextBounds(text, 0, text.length(), bounds);
            int x = (bitmap.getWidth() - bounds.width()) / 6;
            int y = (bitmap.getHeight() + bounds.height()) +2;

            canvas.drawText(text, x * scale, y * scale, paint);
            return bitmap;
        } catch (Exception e) {
            return null;
        }
    }


    public static Bitmap getMardBitmap(String text, int imgResourceId, Context mContext){
        Resources resources = mContext.getResources();
        Bitmap bitmap = BitmapFactory.decodeResource(resources, imgResourceId);
        return addBitmap(getNewBitMap(text,mContext),scaleBitmap(bitmap,0.5f));
    }


    public static Bitmap getMyBitmap(String pm_val, int imgResourceId, Context mContext) {
        Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(),
                imgResourceId);
        bitmap = Bitmap.createBitmap(bitmap, 0 ,0, bitmap.getWidth(),
                bitmap.getHeight());
        Canvas canvas = new Canvas(bitmap);
        TextPaint textPaint = new TextPaint();
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(22f);
        textPaint.setColor(mContext.getResources().getColor(R.color.color_gray));
        canvas.drawText(pm_val, 17, 35 ,textPaint);// 设置bitmap上面的文字位置
        return bitmap;
    }

    /**
     * 纵向拼接
     * <功能详细描述>
     * @param first
     * @param second
     * @return
     */
    private static Bitmap addBitmap(Bitmap first, Bitmap second) {
        int width = Math.max(first.getWidth(),second.getWidth());
        int height = first.getHeight() + second.getHeight();
        int sw = width-second.getWidth()==0?0:(width-second.getWidth())/3;
        Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(first, 0, 0, null);
        canvas.drawBitmap(second, sw, first.getHeight(), null);
        return result;
    }

    /**
     * 按比例缩放图片
     *
     * @param origin 原图
     * @param ratio  比例
     * @return 新的bitmap
     */
    public static Bitmap scaleBitmap(Bitmap origin, float ratio) {
        if (origin == null) {
            return null;
        }
        int width = origin.getWidth();
        int height = origin.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(ratio, ratio);
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        if (newBM.equals(origin)) {
            return newBM;
        }
        origin.recycle();
        return newBM;
    }

    /**
     * 根据文字创建一个 bitmap  ， 打印的位图需要 黑字 白底
     *
     * @param text

     * @return
     */
    public static Bitmap getNewBitMap(String text, Context mContext) {
        Resources resources = mContext.getResources();
        float scale = resources.getDisplayMetrics().density;
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); // new antialised Paint
        paint.setColor(Color.rgb(110, 110, 110));       // text color - #3D3D3D
        paint.setTextSize((int)(13 * scale));           // text size in pixels
        paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY); // text shadow
        if(text.length()<9){
            text = "    "+text+"   ";
        }


        // draw text to the Canvas center
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int width = bounds.width();
        int height = bounds.height();

        Bitmap newBitmap = createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas();
        canvas.setBitmap(newBitmap);
//        canvas.drawColor(Color.w);

        canvas.drawBitmap(newBitmap, 0, 0, null);
        TextPaint textPaint = new TextPaint();
        //       String familyName ="宋体";
        //  Typeface font = Typeface.create(familyName,Typeface.BOLD);
        // textPaint.setTypeface(font);
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(height * 2 / 3);
//        textPaint.setColor(Color.rgb(0, 0, 0));
        textPaint.setColor(Color.GRAY);
        //     "在Android开发中，Canvas.drawText不会换行，即使一个很长的字符串也只会显示一行，超出部分会隐藏在屏幕之外.StaticLayout是android中处理文字的一个工具类，StaticLayout 处理了文字换行的问题";

        StaticLayout sl = new StaticLayout(text, textPaint, newBitmap.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
        textPaint.setStyle(Paint.Style.FILL);
        canvas.translate(0, height / 10);
        sl.draw(canvas);
        return newBitmap;
    }

    public static JSONObject moveCableWellPhoto(String path, String id, String mate){
        String[] types = {"jgqm","kjh","sgh","pmb","pmd","pmn","pmx","yh","gp","qt"};
        String[] pctypes = {"jinggaiImages","kaijinghImages","shigonghImages","duanmianNorthImages","duanmianEastImages","duanmianSouthImages","duanmianWestImages","yinhuanImages","guapaiImages","qitaImages"};
        return movePhoto(path,id,mate,types,pctypes);
    }

    public static JSONObject moveConnectorPhoto(String path, String id, String mate){
        String[] types = {"jt"};
        String[] pctypes = {"jietouImages"};
        return movePhoto(path,id,mate,types,pctypes);
    }

    public static JSONObject moveSurplusPhoto(String path, String id, String mate){
        String[] types = {"py"};
        String[] pctypes = {"panyuImages"};
        return movePhoto(path,id,mate,types,pctypes);
    }

    private static JSONObject movePhoto(String path, String id, String mate,String[] types,String[] pctypes){
        String nPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/CJAPP/images/";
        JSONObject jsonObject;
        if(mate==null || mate.equals("")){
            jsonObject = new JSONObject();
        }else{
            jsonObject = JSONObject.parseObject(mate);
        }
        for(int i = 0 ;i<types.length;i++){
            JSONArray jsonArray = new JSONArray();
            List<String> imageList = new ArrayList<>();
            imageList.addAll(Utils.getFilesAllName(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/ZDApp/" + path + "/"+id+"/"+types[i]+"/"));
            for(String imagePath:imageList){
                File file = new File(imagePath);
                String fileName = file.getName();
                JSONObject imagej = new JSONObject();
                imagej.put("id",UuidUtils.getStringID());
                imagej.put("diskName",fileName);
                imagej.put("thumbUrl","/api/file/"+fileName);
                imagej.put("url","/api/file/"+fileName);
                jsonArray.add(imagej);
                copyFile(imagePath,nPath+fileName);
            }
            jsonObject.put(pctypes[i],jsonArray);
        }
        return jsonObject;
    }


    public static JSONObject moveEquipmentPhoto(String path, String id, String mate){
        String[] types = {"mp","qm","gt","gd"};
        String[] pctypes = {"mingpaiImages","quanmaoImages","gantaImages","guaidianImages"};
        return movePhoto(path,id,mate,types,pctypes);
    }


    public static boolean isNumeric(String string){
        if(string.equals("")){
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(string).matches();
    }

    /** 
          * 字符串是否为数字，包含小数
          * @author 许凯勋
          * @date 2016年11月20日 下午11:35:36 
          * @param str
          * @return  
          */
    public static boolean isNumber(String str){
        String reg = "^[0-9]+(.[0-9]+)?$";
        return str.matches(reg);
    }

    public static boolean aBigger(float f1,float f2) {
        BigDecimal b1 = new BigDecimal(f1);
        BigDecimal b2 = new BigDecimal(f2);
        if (b1.compareTo(b2) >-1) {
           return true;
        } else {
            return false;
        }
    }

    public static String getName(int i){
        Format f1 = new DecimalFormat("000");
        return f1.format(i);

    }
    //去除000递增
    public static String getZyName(int i){
//        Format f1 = new DecimalFormat("000");
//        return f1.format(i);
        return "";

    }
    public static String getNameString(String text){
        //只识别"号"前面的数字
//        String pattern = "(?<=\\D|^)(\\d+)(?=号)";
        //识别最后一个数字进行递增
        String pattern = "\\d+(?![\\d\\D]*\\d)";


        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(text);

        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String numberStr = m.group(0); // 获取匹配到的数字部分
            int number = Integer.parseInt(numberStr); // 将数字部分转换为整数
            int increasedNumber = number + 1; // 递增数字部分
            m.appendReplacement(sb, String.valueOf(increasedNumber)); // 替换原文本中的数字部分
        }
        m.appendTail(sb);
        return sb.toString();
    }

//    public static String incrementNumberInText(String text) {
//        String pattern = "("(\\d+)\\s*号.*")";
//        Pattern r = Pattern.compile(pattern);
//        Matcher m = r.matcher(text);
//
//        if (m.find()) {
//            String numberStr = m.group(0); // 获取匹配到的数字部分
//            int number = Integer.parseInt(numberStr); // 将数字部分转换为整数
//            int increasedNumber = number + 1; // 递增数字部分
//            return text.replace(numberStr, String.valueOf(increasedNumber)); // 替换原文本中的数字部分
//        } else {
//            return text; // 如果没有匹配到数字部分，则原样返回文本
//        }
//    }


    public static String cleanName(String name){
        if(name==null || name.length()<=3){
            return name;
        }

        char[] chars = name.toCharArray();
        boolean s = true;
        for(int i = chars.length;i>chars.length-3;i--){
            if(!Character.isDigit(chars[i-1])){
                s = false;
            }
        }
        if(s){
            return name.substring(0,name.length()-3);
        }
        return name;
    }


    /**
     * 复制文件夹及其中的文件
     *
     * @param oldPath String 原文件夹路径 如：data/user/0/com.test/files
     * @param newPath String 复制后的路径 如：data/user/0/com.test/cache
     * @return <code>true</code> if and only if the directory and files were copied;
     *         <code>false</code> otherwise
     */
    public static boolean copyFolder(String oldPath, String newPath) {
        try {
            File newFile = new File(newPath);
            if (!newFile.exists()) {
                if (!newFile.mkdirs()) {
                    Log.e("--Method--", "copyFolder: cannot create directory.");
                    return false;
                }
            }
            File oldFile = new File(oldPath);
            String[] files = oldFile.list();
            File temp;
            for (String file : files) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file);
                } else {
                    temp = new File(oldPath + File.separator + file);
                }

                if (temp.isDirectory()) {   //如果是子文件夹
                    copyFolder(oldPath + "/" + file, newPath + "/" + file);
                } else if (!temp.exists()) {
                    Log.e("--Method--", "copyFolder:  oldFile not exist.");
                    return false;
                } else if (!temp.isFile()) {
                    Log.e("--Method--", "copyFolder:  oldFile not file.");
                    return false;
                } else if (!temp.canRead()) {
                    Log.e("--Method--", "copyFolder:  oldFile cannot read.");
                    return false;
                } else {
                    FileInputStream fileInputStream = new FileInputStream(temp);
                    FileOutputStream fileOutputStream = new FileOutputStream(newPath + "/" + temp.getName());
                    byte[] buffer = new byte[1024];
                    int byteRead;
                    while ((byteRead = fileInputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, byteRead);
                    }
                    fileInputStream.close();
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }

                /* 如果不需要打log，可以使用下面的语句
                if (temp.isDirectory()) {   //如果是子文件夹
                    copyFolder(oldPath + "/" + file, newPath + "/" + file);
                } else if (temp.exists() && temp.isFile() && temp.canRead()) {
                    FileInputStream fileInputStream = new FileInputStream(temp);
                    FileOutputStream fileOutputStream = new FileOutputStream(newPath + "/" + temp.getName());
                    byte[] buffer = new byte[1024];
                    int byteRead;
                    while ((byteRead = fileInputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, byteRead);
                    }
                    fileInputStream.close();
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
                 */
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
